package com.heima.article.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ApCollectionService;
import com.heima.common.exception.CustomException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
//import io.seata.spring.annotation.GlobalTransactional;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;

import com.heima.feigns.user.UserFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ApArticleServiceimpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    @Resource
    ApArticleContentMapper apArticleContentMapper;

    @Resource
    ApArticleConfigMapper apArticleConfigMapper;

    @Resource
    ApArticleMapper apArticleMapper;

    @Resource
    BehaviorFeign behaviorFeign;

    @Resource
    UserFeign userFeign;

    @Resource
    ApCollectionService apCollectionService;

    @Transactional
    public ResponseResult saveAllData(ArticleDto articleDto) {
        //设置文章表数据
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
        apArticle.setComment(0);
        apArticle.setViews(0);
        apArticle.setCollection(0);
        apArticle.setLikes(0);

        //设置文章内容表数据
        ApArticleContent apArticleContent = new ApArticleContent();
        BeanUtils.copyProperties(articleDto, apArticleContent);

        //设置文章配置表数据
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);

        //根据作者id查询文章
        ApArticle articleRes = apArticleMapper.selectOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getAuthorId, articleDto.getAuthorId()));

        //文章不为空则为修改
        if (articleRes == null) { //添加
            this.save(apArticle);
            apArticleContentMapper.insert(apArticleContent);
            apArticleConfigMapper.insert(apArticleConfig);

        } else {              //修改
            ApArticle article = this.getById(articleDto.getId());
            //判断文章是否存在
            if (article == null) {
                log.error("文章不存在===>{}", articleDto.getId());
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //修改文章
            this.updateById(apArticle);

            //根据文章id判断文章内容是否存在
            ApArticleContent apArticleContentRes = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            if (apArticleContentRes == null) {
                log.error("文章内容不存在===>{}", apArticle.getId());
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //修改文章内容
            apArticleContentMapper.updateById(apArticleContent);

            //根据文章id判断文章配置是否存在
            ApArticleConfig apArticleConfigRes = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));
            if (apArticleConfigRes == null) {
                log.error("文章配置不存在===>{}", apArticle.getId());
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //修改文章配置
            apArticleConfigMapper.updateById(apArticleConfig);
        }

        return ResponseResult.okResult(apArticle.getId());
    }

    @Value("${file.oss.web-site}")
    String webSite;


    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //参数校验
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        if (dto.getSize() == null) {
            dto.setSize(10);
        }
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }

        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        //查询
        List<ApArticle> apArticleList = apArticleMapper.loadArticleList(dto, loadtype);

        //返回结果
        ResponseResult result = ResponseResult.okResult(apArticleList);

        result.setHost(webSite);

        return result;
    }

    @Override
    public ResponseResult loadArtilceInfo(ArticleInfoDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据文章id查询文章
        ApArticle apArticle = this.getById(dto.getArticleId());
        //判断文章是否存在
        if (apArticle == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //查看文章配置是否存在
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, dto.getArticleId()));

        if (apArticleConfig == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章配置不存在");
        }

        //查看文章内容是否存在
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getArticleId()));

        if (apArticleContent == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章内容不存在");
        }

        //封装返回数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("config", apArticleConfig);
        resultMap.put("content", apArticleContent);
        ResponseResult result = ResponseResult.okResult(resultMap);
        result.setHost(webSite);
        return result;

    }


    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        if (dto.getArticleId() == null || dto.getAuthorId() == null || dto.getEquipmentId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        //查询行为实体是否存在
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());

        HashMap<String, Object> map = new HashMap<>();
        map.put("isfollow", false);
        map.put("iscollection", false);
        map.put("islike", false);
        map.put("isunlike", false);
        if (behaviorEntry == null) {
            return ResponseResult.okResult(map);
        }

        //查询收藏
        ApCollection apCollection = apCollectionService.getOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId, dto.getArticleId()).eq(ApCollection::getEntryId, behaviorEntry.getId()));

        if (apCollection != null) {
            map.put("iscollection", true);
        }


        //查询是否喜欢
        ApArticleRelationDto articleRelationDto = new ApArticleRelationDto();
        articleRelationDto.setArticleId(dto.getArticleId());
        articleRelationDto.setEntryId(user.getId());
        articleRelationDto.setType((short) 1);
        Map apArticleRelation = behaviorFeign.findApArticleRelation(articleRelationDto);
        map.putAll(apArticleRelation);


        //查询是否点赞
        ApUserFollow userFollow = userFeign.findByUserIdAndFollowId(user.getId(), dto.getAuthorId());
        if (userFollow != null) {
            map.put("isfollow", true);
        }

        return ResponseResult.okResult(map);

    }

    @Override
    public List<ApArticle> findAllArticles() {

        return apArticleMapper.findAllArticles();
    }
}
